<script setup lang="ts">
import {onMounted, ref} from 'vue';
import Flow from "@/views/common/templatedesign/flow.vue";
import Form from "@/views/common/templatedesign/form.vue";
import Table from "@/views/common/templatedesign/table.vue";
import Base from "@/views/common/templatedesign/base.vue";

import {useRoute} from "vue-router";
import {useMessage} from "naive-ui";
import {fetchGetTemplate, fetchSaveFlowData, fetchSaveFormData} from "@/service/api/template";
import type {Field} from "@/components/f_flow/render/type";
import FlowDeployDrawer from "@/views/common/templatedesign/flow-deploy-drawer.vue";


const route = useRoute()
const current = ref<number>(2);
const form = ref();
const flow = ref();
const base = ref();
const tabled = ref();
const flowDeployDrawer = ref();
const message = useMessage();
const contentHeight = ref(110);
contentHeight.value = window.outerHeight - 300;
const templateId = ref<number>(route.query.templateId ? Number(route.query.templateId) : 0);
const templateData = ref<Api.Entity.Template>({
  id: null,
  name: '',
  company: null,
  flowData: {},
  formData: {},
  tableData: {},
  role: [],
});
const flowFormFields = ref<Field[]>([]);

async function getTemplateData() {
  if (templateId.value) {
    fetchGetTemplate(templateId.value).then(res => {
        if (res.data) {
          templateData.value = res.data;
          if (Object.keys(templateData.value.formData).length > 0) {
            form.value.setData(templateData.value.formData);
          }
          if (Object.keys(templateData.value.flowData).length > 0) {
            flow.value.setProcessData(templateData.value.flowData);
          }
          base.value.setData(templateData.value)
          if (templateData.value.formData.schemas) {
            flowFormFields.value = convertToFlowFormFields(templateData.value.formData.schemas);
            flow.value.setFields(flowFormFields.value);
          }
          // console.log("flowFormFields:", flowFormFields.value)

        }
      }
    );
  }
}

//递归转换成流程表单字段
function convertToFlowFormFields(schemas: any) {
  let fields: Field[] = [];
  // console.log("convertToFlowFormFields:",schemas)
  schemas.forEach((item: any) => {
    let child_fields: Field[] = [];
    if (item.type === 'page') {
      fields = convertToFlowFormFields(item.children);
      //如果是page，跳过
    } else if (item.type === 'form') {
      fields = convertToFlowFormFields(item.children);
      //如果是form，跳过
    } else {
      // if (item.children.length > 0) {
      //   child_fields = convertToFlowFormFields(item.children);
      // }
      let name = '';
      if (item.type == 'number') {
        name = 'ElInputNumber';
      } else if (item.type == 'input') {
        name = 'ElInput';
      }

      fields.push({
        id: item.id,
        type: 'formItem',
        label: item.label,
        name: name,
        value: null,
        readonly: false,
        required: false,
        hidden: false,
        children: child_fields,
        props: item.componentProps
      })
    }
  })
  return fields;
}

// 保存表单数据
async function saveFormData() {
  templateData.value.formData = form.value.getData();
  if (templateData.value.formData && templateData.value.formData.schemas) {
    flowFormFields.value = convertToFlowFormFields(templateData.value.formData.schemas);
    // console.log("flowFormFields:", flowFormFields.value)
    flow.value.setFields(flowFormFields.value);
  }
  const {error} = await fetchSaveFormData({
    company: null,
    name: "",
    id: templateId.value,
    formData: templateData.value.formData
  });
  if (!error) {
    await getTemplateData();
  } else {
    message.error(error.message);
  }
}

function saveTableData() {
  tabled.value.save();
}

// 保存流程数据
async function saveFlowData(d: any) {
  templateData.value.flowData = flow.value.getProcessData();
  const {error} = await fetchSaveFlowData({
    company: null,
    name: "",
    id: templateId.value,
    flowData: templateData.value.flowData,
    processModel: {
      code: d.code,
      name: d.name,
      icon: {
        name: 'el:HomeFilled',
        color: '#409EFF'
      },
      process: d.process,
      enable: true,
      version: 1,
      sort: 0,
      groupId: '',
      remark: ''
    }
  });
  if (!error) {

  } else {
    message.error(error.message);
  }
}

// 跳转上一步下一步触发事件
function stepUpdate(index: number) {
  // let val = form.value.getData();
}

function nextStep() {
  if (current.value >= 5) {
    current.value = 5
  } else {
    current.value++
  }
}

function prevStep() {
  if (current.value === 0) {
    current.value = 0
  } else {
    current.value--
  }
}

function deploy(callback:Function) {
  flow.value.deploy({
    id: templateId.value,
  },  callback);
}

function openDeployDrawer() {
  flowDeployDrawer.value.open();
}

onMounted(() => {
  getTemplateData();
  window.addEventListener('keydown', handleEvent)
});

const handleEvent = async (event: any) => {
  if (event.keyCode == 83) {
    if (event.ctrlKey && event.code === 'KeyS') {
      event.preventDefault()
      event.returnValue = false
      // 执行保存操作
      if (current.value == 3) {
        //随机字符串
        let code = Math.random().toString(36).slice(-8);
        if (templateData.value.flowData.model_code) {
          code = templateData.value.flowData.model_code
        }
        await saveFlowData({
          code: code,
          name: templateData.value.name,
          process: flow.value.getProcessData()
        });
      }
      if (current.value == 2) {
        await saveFormData();
      }
      if (current.value == 4) {
        saveTableData();
      }

      message.success('保存成功');
    }
  }
}
</script>

<template>
  <div class="flex-vertical-stretch gap-16px <sm:overflow-auto">
    <NCard title="" :bordered="false" size="small" class="card-wrapper ">
      <n-space vertical size="large">
        <n-layout>
          <n-layout-content :content-style="{'padding': '5px 5px '}">
            <n-steps v-model:current="current" @update-current="stepUpdate">
              <n-step title="基础信息">

              </n-step>
              <n-step title="表单设计">

              </n-step>
              <n-step title="流程设计">

              </n-step>
              <n-step title="表格设计">

              </n-step>
              <n-step title="高级设置">

              </n-step>
            </n-steps>
            <div class="design-container" :style="{'height': contentHeight +'px','text-align':'center'}"
                 v-show=" current == 1">
              <n-flex justify="center">
                <Base ref="base"/>
              </n-flex>
            </div>
            <div class="design-container" :style="{'max-height': contentHeight +'px'}" v-show=" current == 2">
              <Form ref="form"/>
            </div>
            <div class="design-container" :style="{'max-height': contentHeight +'px'}" v-show=" current == 3">
              <Flow ref="flow" :fields="flowFormFields"/>
              <FlowDeployDrawer ref="flowDeployDrawer" :template="templateData" @deploy-model="deploy"/>
            </div>
            <div class="design-container" :style="{'height': contentHeight +'px'}" v-show=" current == 4">
              <Table ref="tabled" :template-id="templateId"/>
            </div>
            <div class="design-container" :style="{'height': contentHeight +'px'}" v-show=" current == 5">
              <Bpmn/>
            </div>
          </n-layout-content>
          <n-layout-footer style="">
            <n-flex justify="center" style="background-color: white;">
              <n-space>
                <n-button strong secondary v-show="current > 1" @click="prevStep">
                  上一步
                </n-button>
                <n-button strong secondary v-show="current < 5" @click="nextStep">
                  下一步
                </n-button>
                <n-button type="info" v-show="current == 3" @click="openDeployDrawer">
                  流程部署
                </n-button>
                <n-button type="success" v-show="current == 5">
                  保存
                </n-button>
              </n-space>
            </n-flex>
          </n-layout-footer>
        </n-layout>
      </n-space>
    </NCard>
  </div>
</template>

<style scoped>
:deep(.n-card__content) {
}

:deep(.node-container) {
  width: 100%;
}

.design-container {
  margin-top: 1rem;
  overflow: auto;
}
</style>
